import { store } from "../redux/store"
import { useState, useRef, useEffect } from 'react'

let URLAPI = 'https://tweetwallet.io/api';
let URLUPLOAD = 'https://tweetwallet.io/upload';
let URLUWSAPI = 'https://tweetwallet.io/wsapi';

const http = () => {
    const { app } = store.getState()
    const [token, setToken] = useState(null)
    useEffect(() => {
        setToken(token)
    }, [app.token])

    const header: any = {
        // "Content-type": "multipart/form-data"
    }
    const token_type = "Bearer"
    const formData = (params: any) => {
        let formData = new FormData();
        for (let i in params) {
            formData.append(i, params[i])
        }
        return formData
    }
    const get = (url: string, params: any) => {
        if (params) {
            let paramsArray: any = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }

        if (token) {
            header.Authorization = token_type + ' ' + token
        }
        return new Promise(function (resolve, reject) {
            fetch(URLAPI + url, { headers: header })
                .then((response) => response.json()
                    //将返回数据转化为json，也可以转为text(),否则无法看到返回数据,且必须回调才可以看到
                )
                .then((responseData) => {
                    resolve(responseData);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    const post = (url: string, params: any) => {
        return new Promise(async function (resolve, reject) {

            if (token) {
                header.Authorization = token_type + ' ' + token
            }
            fetch(URLAPI + url, {
                method: 'POST',
                headers: header,
                body: formData(params)  //body参数，通常需要转换成字符串后服务器才能解析
            }).then((response) => response.json())
                .then((responseData) => {
                    resolve(responseData);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    const wsapiPost = (url: string, params: any) => {
        return new Promise(async function (resolve, reject) {

            if (token) {
                header.Authorization = token_type + ' ' + token
            }
            fetch(URLUWSAPI + url, {
                method: 'POST',
                headers: header,
                body: formData(params)  //body参数，通常需要转换成字符串后服务器才能解析
            }).then((response) => response.json())
                .then((responseData) => {
                    resolve(responseData);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    const wsapiGet = (url: string, params: any) => {
        if (params) {
            let paramsArray: any = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }

        if (token) {
            header.Authorization = token_type + ' ' + token
        }
        return new Promise(function (resolve, reject) {
            fetch(URLUWSAPI + url, { headers: header })
                .then((response) => response.json()
                    //将返回数据转化为json，也可以转为text(),否则无法看到返回数据,且必须回调才可以看到
                )
                .then((responseData) => {
                    resolve(responseData);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    const upload = (url: string, params: any) => {
        return new Promise(async function (resolve, reject) {

            if (token) {
                header.Authorization = token_type + ' ' + token
            }
            const formData = new FormData()
            if (params instanceof Array) {
                for (let index = 0; index < params.length; index++) {
                    const element = params[index];
                    let uri = element.uri
                    let uriArr = uri.split('/')
                    let name = uriArr[uriArr.length - 1]
                    formData.append('f', {
                        uri,
                        name: element.fileName || name,
                        type: element.type,
                    })
                }
            } else {
                let uriArr = params.uri.split('/')
                let name = uriArr[uriArr.length - 1]
                formData.append('f', {
                    uri: params.uri,
                    name: params.fileName || name,
                    type: params.type,
                })
            }

            fetch(URLUPLOAD + url, {
                method: 'POST',
                headers: header,
                body: formData  //body参数，通常需要转换成字符串后服务器才能解析
            }).then((response) => response.json())
                .then((responseData) => {
                    resolve(responseData);
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    return {
        get,
        post,
        wsapiPost,
        wsapiGet,
        upload,
    }
};

//导出
export default httpApiNetwork
